package com.y.game.listener;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import com.y.game.emtity.Ground;
import com.y.game.emtity.Shape;
import com.y.game.emtity.ShapeFactory;
import com.y.game.view.GamePanel;

/**
 * 监听器类 用于监听 用户按键 以及 图形定时下落变化
 */
public class GameListener extends KeyAdapter implements IShapeListener {
	
	private GamePanel gamePanel;
	private ShapeFactory shapeFactory;
	private Shape shape;
	private Ground ground;
	
	public GameListener(GamePanel gamePanel, ShapeFactory shapeFactory, Ground ground) {
		this.gamePanel = gamePanel;
		this.shapeFactory = shapeFactory;
		this.ground = ground;
	}
	
	/**
	 *  处理用户按键 按键后需要重新显示
	 */
	@Override
	public void keyPressed(KeyEvent e) {
		switch(e.getKeyCode()) {
		case KeyEvent.VK_UP :
			if(ground.isMoveable(shape, Shape.ROTATE)) {
				shape.rotate();
			}
			break;
		case KeyEvent.VK_RIGHT :
			if(ground.isMoveable(shape, Shape.MOVERIGHT)) {
				shape.moveRight();
			}
			break;
		case KeyEvent.VK_DOWN :
			if(ground.isMoveable(shape, Shape.MOVEDOWN)) {
				shape.moveDown();
			}
			break;
		case KeyEvent.VK_LEFT :
			if(ground.isMoveable(shape, Shape.MOVELEFT)) {
				shape.moveLeft();
			}
			break;
		}
		
		// 游戏面板重新绘制
		gamePanel.display(ground, shape);
	}

	// 图形定时下落也需要重新绘制游戏面板
	@Override
	public void moveDown() {
		gamePanel.display(ground, shape);
	}
	
	@Override
	public synchronized boolean isShapeMoveable() {
		if(ground.isMoveable(shape, Shape.MOVEDOWN)) {
			return true;
		}
		
		// 成为障碍物
		ground.accept(shape);
		
		this.newGame();
		
		return false;
	}
	
	// new game
	public void newGame() {
		this.shape = shapeFactory.getShape();
		this.shape.addShapeListener(this);
	}
}
